from django.db.models import Q
from django.shortcuts import render
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *
import time
import datetime
import random


# Create your views here.

# 注册
class RegisterView(APIView):
    def post(self, request):
        username = request.data.get('username', None)
        password = request.data.get('password', None)
        phone = request.data.get('phone', None)
        role = request.data.get('role', None)
        money = request.data.get('money', None)
        user_obj = User.objects.filter(username=username).first()
        if user_obj:
            return Response({'msg': '用户已存在', 'code': 400})
        try:
            user = User(username=username, password=password, phone=phone, role_id=role, money=money)
            user.save()
            return Response({"msg": "注册成功", 'code': 200})
        except Exception as e:
            print(e)
            return Response({'msg': '用户已存在', 'code': 405})


# 登录
class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username', None)
        password = request.data.get('password', None)
        user_obj = User.objects.filter(Q(username=username) | Q(phone=username), password=password).first()
        if user_obj:
            return Response({'msg': '登录成功',
                             'code': 200,
                             'uid': user_obj.id,
                             'username': user_obj.username,
                             'role': user_obj.role.name,
                             "right": user_obj.role.state
                             })
        else:
            return Response({'msg': '登录失败', 'code': 400})


# 教练
class CoachView(APIView):
    # 添加
    def post(self, request):
        name = request.data.get('name', None)
        age = request.data.get('age', None)
        gender = request.data.get('gender', None)
        introduce = request.data.get('introduce', None)
        level = request.data.get('level', None)
        coach_obj = Coach.objects.filter(name=name).first()
        if coach_obj:
            return Response({'msg': '教练已存在不要在添加了', 'code': 400})
        try:
            coach = Coach(name=name, age=age, gender=gender, introduce=introduce, level=level)
            coach.save()
            return Response({'msg': '添加教练成功', 'code': 200})
        except Exception as e:
            print(e)
            return Response({'msg': '教练已存在', 'code': 400})

    # 获取等级教练
    def get(self, request):
        level = request.GET.get("level")
        print(level, "********")
        if level == "高级会员":
            coach_ids = Order.objects.filter(state=1).values_list('coach_id')
            coach_list = Coach.objects.exclude(id__in=coach_ids)
            coach_ser = ShowCoachSer(coach_list, many=True)
            return Response({'msg': '获取成功', 'code': 200, 'data': coach_ser.data})
        else:
            if level == "普通会员":
                # coach_list = Coach.objects.filter(level__gt=1).all()
                coach_ids = Order.objects.filter(state=1).values_list('coach_id')  # 以列表形式取出所有在上课的教练
                coach_list = Coach.objects.filter(level=1).exclude(id__in=coach_ids)  # 获取没上课教练信息
                coach_ser = ShowCoachSer(coach_list, many=True)
                return Response({'msg': '获取成功', 'code': 200, 'data': coach_ser.data})


# 抢课
class CoachTakeView(APIView):
    def post(self, request):
        user_id = request.data.get("user_id")
        coach_id = request.data.get("coach_id")

        order_obj = Order.objects.filter(user_id=user_id, coach_id=coach_id, state=1)
        if order_obj:
            return Response({'msg': "已抢课", "code": 400})
        else:
            Order.objects.create(user_id=user_id, coach_id=coach_id, state=1, start_time=int(time.time())).save()
            return Response({'msg': "抢课成功", "code": 200})

    def get(self, request):
        uid = request.GET.get("uid")
        print(uid)
        coach_id = request.GET.get("coach_id")
        print(coach_id)
        coach_ids = Order.objects.filter(coach_id=coach_id, state=0).values_list('coach_id')
        print(coach_ids)
        # 只看到未被抢课的教练

        order_obj = Coach.objects.filter(id__in=coach_ids)
        order = CoachSer(order_obj, many=True)
        return Response({'data': order.data, 'code': 200})


# 下课
class OrderView(APIView):
    def get(self, request):
        uid = request.GET.get("uid")
        print(uid)
        coach_id = request.GET.get("coach_id")
        print(coach_id)
        # 获取哪位教练
        order_obj = Order.objects.filter(coach_id=coach_id, user_id=uid).first().coach
        print(order_obj)
        order = CoachSer(order_obj)
        return Response({'data': order.data, 'code': 200})

    def post(self, request):
        coach_id = request.data.get("coach_id")
        order_obj = Order.objects.filter(coach_id=coach_id, state=1)  # 获取该上课教练
        if order_obj:
            start_time = order_obj.first().start_time  # 获取上课时间
            end_time = int(time.time())  # 获取下课时间
            order_num = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(100000, 999999))
            cost_money = (end_time - start_time) * 200
            if 3000 <= cost_money < 5000:
                cost_money = cost_money * 0.8
            elif cost_money >= 5000:
                cost_money = cost_money * 0.5
            if Coach.objects.get(id=coach_id).level == 0:
                order_obj.update(end_time=end_time, cost_money=cost_money, state=0,
                                 ordernum=order_num)  # 普通结账

            else:
                cost_money = (end_time - start_time) * 500
                if 3000 <= cost_money < 5000:
                    cost_money = cost_money * 0.8
                elif cost_money >= 5000:
                    cost_money = cost_money * 0.5
                order_obj.update(end_time=end_time, cost_money=cost_money, state=0,
                                 ordernum=order_num)  # 高级教练结账结账
            return Response({'msg': "已下课,并计算金额", "code": 200})
        else:
            return Response({'msg': "未抢课", "code": 200})


# 教练订单展示
class OrderListView(APIView):
    def get(self, request):
        order = Order.objects.filter(state=0)
        order_ser = OrderListSer(order, many=True)
        return Response(order_ser.data)


# 打折
class UserDiscountView(APIView):
    def post(self, request):
        # order = Order.objects.filter(Q(cost_money__gte=3000))
        order = Order.objects.filter(cost_money__in=3000)
        if order:
            pass
            # order.update(money = ()  )


from django.db.models import Count, Sum


# 总金额
class UserAccountView(APIView):
    def get(self, request):
        orders = Order.objects.all()
        list_money = []
        for o in orders:
            list_money.append(o.cost_money)
        total_money = sum(list_money)
        return Response(total_money)


# 优秀教练
class GoodCoachView(APIView):
    def get(self, request):
        orders = Order.objects.values('coach__name').annotate(num=Count('coach'))
        print(orders)
        result = sorted(orders, key=lambda e: e['num'], reverse=True)[0]
        # return Response(1)
        return Response(result)


# 有钱学员
class GoodUserView(APIView):
    def get(self, request):
        orders = Order.objects.values('user__username').annotate(money=Sum('cost_money'))
        print(orders)
        result = sorted(orders, key=lambda e: e['money'], reverse=True)[0]
        # return Response(1)
        return Response(result)


# 结合
class CombineView(APIView):
    def get(self, request):
        state = request.GET.get("state")
        if state == "1":
            orders = Order.objects.values('coach__name').annotate(num=Count('coach'))
            print(orders)
            result = sorted(orders, key=lambda e: e['num'], reverse=True)[0]
            # return Response(1)
            return Response(result)
        else:
            if state == "2":
                orders = Order.objects.values('user__username').annotate(money=Sum('cost_money'))
                print(orders)
                result = sorted(orders, key=lambda e: e['money'], reverse=True)[0]
                # return Response(1)
                return Response(result)
